<template>
  <div :style="{margin: '0 auto',width:'100%'}">
    <el-row :gutter="60" class="main">
      <el-form ref="formRef" :model="dataForm" :rules="dataRule" size="medium" label-width="100px" label-position="top"
               :disabled="setting.readonly">
        <template v-if="!loading && formOperates">
          <!-- 具体表单 -->
          <el-col :span="4">
            <el-row :gutter="30">
              <el-col :span="24">
                <jnpf-form-tip-item>
                  <JnpfText
                    :textStyle='{"color":"#000000","font-weight":"normal","text-decoration":"none","font-size":12,"line-height":32,"font-style":"normal","text-align":"left"}'>
                  </JnpfText>
                </jnpf-form-tip-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="16" class="project-main">
            <el-row :gutter="30">
              <el-col :span="24">
                <jnpf-form-tip-item>
                  <JnpfText
                    :textStyle='{"color":"#1684FC","font-weight":"bold","text-decoration":"none","font-size":24,"line-height":32,"font-style":"normal","text-align":"center"}'
                    content="数字化改造验收">
                  </JnpfText>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('enterpriseName')">
                <jnpf-form-tip-item
                  label="企业名称" v-if="judgeShow('enterpriseName')" prop="enterpriseName">
                  <JnpfInput v-model="dataForm.enterpriseName" @change="changeData('enterpriseName',-1)"
                             placeholder="自动填充不可修改" :disabled="judgeWrite('enterpriseName')" readonly clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="12" v-if="judgeShow('enterpriseCreditCode')">
                <jnpf-form-tip-item
                  label="企业信用代码" v-if="judgeShow('enterpriseCreditCode')" label-width="125px"
                  prop="enterpriseCreditCode">
                  <JnpfInput v-model="dataForm.enterpriseCreditCode" @change="changeData('enterpriseCreditCode',-1)"
                             placeholder="自动填充不可修改" :disabled="judgeWrite('enterpriseCreditCode')" readonly clearable
                             :style='{"width":"100%"}'>
                  </JnpfInput>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('projectNames')">
                <jnpf-form-tip-item
                  label="项目名称" v-if="judgeShow('projectNames')" prop="projectNames">
                  <JnpfTextarea v-model="dataForm.projectNames" @change="changeData('projectNames',-1)"
                                placeholder="自动填充不可修改" :disabled="judgeWrite('projectNames')" readonly
                                :style='{"width":"100%"}' true type="textarea" :autosize='{"minRows":4,"maxRows":4}'>
                  </JnpfTextarea>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="isShowBudget">
                <jnpf-form-tip-item label="数字化改造产品或服务预算信息" >
                <el-table :data="projectDigitalBudgetList" border>
                  <el-table-column prop="F_Project_Name" label="项目名称" align="center"></el-table-column>
                  <el-table-column prop="digitalBudget" label="数字化改造产品或服务预算" align="center">
                    <el-table-column prop="F_Budget_Name" label="预算名称" align="center">
                      <template slot-scope="scope">
                        <div v-for="item in scope.row.digitalBudget">{{item.F_Budget_Name}}</div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="F_Budget_Money" label="预算金额(万元)" align="center">
                      <template slot-scope="scope">
                        <div v-for="item in scope.row.digitalBudget">{{item.F_Budget_Money}}</div>
                      </template>
                    </el-table-column>
                  </el-table-column>
                </el-table>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="isShowBudget">
                <jnpf-form-tip-item label="其他支出预算" >
                  <el-table :data="otherProjectDigitalBudgetList" border>
                    <el-table-column prop="F_Project_Name" label="项目名称" align="center"></el-table-column>
                    <el-table-column prop="otherDigitalBudget" label="其他支出预算" align="center">
                      <el-table-column prop="F_Budget_Name" label="预算名称" align="center">
                        <template slot-scope="scope">
                          <div v-for="item in scope.row.otherDigitalBudget">{{item.F_Budget_Name}}</div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="F_Budget_Money" label="预算金额(万元)" align="center">
                        <template slot-scope="scope">
                          <div v-for="item in scope.row.otherDigitalBudget">{{item.F_Budget_Money}}</div>
                        </template>
                      </el-table-column>
                    </el-table-column>
                  </el-table>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('digitalProjectContract')">
                <jnpf-form-tip-item label="数字化改造项目服务合同（盖章扫描版） " v-if="judgeShow('digitalProjectContract')"
                                    prop="digitalProjectContract">
                  <div v-for="item in dataForm.digitalProjectContract" class="file-main">
                    <label>{{ item.projectName }} ：</label>
                    <JnpfUploadFile v-model="item.projectFiles"
                                    disabled
                                    detailed :fileSize="10" sizeUnit="MB" :limit="9" pathType="defaultPath"
                                    :isAccount="0" buttonText="点击上传">
                    </JnpfUploadFile>
                  </div>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('digitalProjectPlan')">
                <jnpf-form-tip-item label="数字化改造项目方案（盖章扫描版） " v-if="judgeShow('digitalProjectPlan')"
                                    prop="digitalProjectPlan">
                  <div v-for="item in dataForm.digitalProjectPlan" class="file-main">
                    <label>{{ item.projectName }} ：</label>
                    <JnpfUploadFile v-model="item.projectFiles"
                                    disabled
                                    detailed :fileSize="10" sizeUnit="MB" :limit="9" pathType="defaultPath"
                                    :isAccount="0" buttonText="点击上传">
                    </JnpfUploadFile>
                  </div>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('transactionRecords')">
                <jnpf-form-tip-item
                  label="项目投资发票和付款凭证等交易记录（扫描版）" v-if="judgeShow('transactionRecords')" prop="transactionRecords">
                  <JnpfUploadFile v-model="dataForm.transactionRecords" @change="changeData('transactionRecords',-1)"
                                  :disabled="judgeWrite('transactionRecords')" tipText="请上传pdf格式，如有多项材料，请压缩至一个文件夹上传"
                                  accept=".pdf" :fileSize="200" sizeUnit="MB" :limit="1" pathType="defaultPath" :isAccount="0"
                                  buttonText="点击上传">
                  </JnpfUploadFile>
                </jnpf-form-tip-item>
              </el-col>
              <el-col :span="24" v-if="judgeShow('scanningCopy')">
                <jnpf-form-tip-item
                  label="《福州市中小企业数字化转型被改造试点企业项目验收申请函》（盖章扫描版，详见附件）" v-if="judgeShow('scanningCopy')" prop="scanningCopy">
                  <JnpfUploadFile v-model="dataForm.scanningCopy" @change="changeData('scanningCopy',-1)"
                                  :disabled="judgeWrite('scanningCopy')" tipText="请上传pdf格式" accept=".pdf"
                                  :fileSize="200" sizeUnit="MB" :limit="2" pathType="defaultPath" :isAccount="0" buttonText="点击上传">
                  </JnpfUploadFile>
                </jnpf-form-tip-item>
              </el-col>
            </el-row>
          </el-col>
          <!-- 表单结束 -->
        </template>
        <SelectDialog v-if="selectDialogVisible" :config="currTableConf" :formData="dataForm"
                      ref="selectDialog" @select="addForSelect" @close="selectDialogVisible=false"/>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit"/>
  </div>
</template>

<script>
import request from '@/utils/request'
import {mapGetters} from "vuex";
import {getFormById} from '@/api/workFlow/FormDesign'
import comMixin from '@/views/workFlow/workFlowForm/mixin';
import {getDataInterfaceRes} from '@/api/systemData/dataInterface'
import {getDictionaryDataSelector} from '@/api/systemData/dictionary'
import {getDefaultCurrentValueUserId} from '@/api/permission/user'
import {getDefaultCurrentValueDepartmentId} from '@/api/permission/organize'
import {
  getDateDay,
  getLaterData,
  getBeforeData,
  getBeforeTime,
  getLaterTime
} from '@/components/Generator/utils/index.js'
import {thousandsFormat} from "@/components/Generator/utils/index"
import axios from "axios";

export default {
  mixins: [comMixin],
  components: {},
  props: [],
  data() {
    return {
      isShowBudget:false,
      projectDigitalBudgetList: [],
      otherProjectDigitalBudgetList:[],
      dataFormSubmitType: 0,
      continueBtnLoading: false,
      index: 0,
      prevDis: false,
      nextDis: false,
      allList: [],
      visible: false,
      loading: false,
      btnLoading: false,
      formRef: 'formRef',
      setting: {},
      eventType: '',
      userBoxVisible: false,
      selectDialogVisible: false,
      currTableConf: {},
      dataValueAll: {},
      addTableConf: {},
      //可选范围默认值
      ableAll: {},
      tableRows: {},
      Vmodel: "",
      currVmodel: "",
      dataForm: {
        enterpriseName: undefined,
        enterpriseCreditCode: undefined,
        county: undefined,
        phone: undefined,
        projectId: undefined,
        projectNames: undefined,
        digitalProjectContract: [],
        digitalProjectPlan: [],
        transactionRecords: [],
        scanningCopy: [{
          "fileSize": 13824,
          "fileExtension": "docx",
          "name": "福州市中小企业数字化转型被改造试点企业项目验收申请函模板.docx",
          "url": "/api/file/Image/annex/6673de2e60b2091fb22ee52a.docx",
          "fileId": "6673de2e60b2091fb22ee52a.docx"
        }],
        acceptIspass: undefined,
        isconfirm: "0",
        rectificationOpinions: undefined,
        digitizationLevel: undefined,
        performanceAcceptanceReport: [],
        digitalEvaluationReport: [],
        status: undefined,
        creatoruserid: undefined,
        creatortime: undefined,
        lastmodifyuserid: undefined,
        lastmodifytime: undefined,
      },
      tableRequiredData: {},
      dataRule:
        {
          enterpriseName: [
            {
              required: true,
              message: '自动填充不可修改',
              trigger: 'blur'
            },
          ],
          enterpriseCreditCode: [
            {
              required: true,
              message: '自动填充不可修改',
              trigger: 'blur'
            },
          ],
          county: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          projectId: [
            {
              required: true,
              message: '自动填充不可修改',
              trigger: 'blur'
            },
          ],
          projectNames: [
            {
              required: true,
              message: '自动填充不可修改',
              trigger: 'blur'
            },
          ],
          digitalProjectContract: [
            {
              required: true,
              message: '请至少选择一个',
              trigger: 'change'
            },
          ],
          digitalProjectPlan: [
            {
              required: true,
              message: '请至少选择一个',
              trigger: 'change'
            },
          ],
          transactionRecords: [
            {
              required: true,
              message: '请至少选择一个',
              trigger: 'change'
            },
          ],
          scanningCopy: [
            {
              required: true,
              message: '请至少选择一个',
              trigger: 'change'
            },
          ],
        },
      countyOptions: [{"fullName": "鼓楼区", "id": "鼓楼区"}, {"fullName": "台江区", "id": "台江区"}, {
        "fullName": "仓山区",
        "id": "仓山区"
      }, {"fullName": "马尾区", "id": "马尾区"}, {"fullName": "晋安区", "id": "晋安区"}, {
        "fullName": "长乐区",
        "id": "长乐区"
      }, {"fullName": "闽侯县", "id": "闽侯县"}, {"fullName": "连江县", "id": "连江县"}, {
        "fullName": "罗源县",
        "id": "罗源县"
      }, {"fullName": "闽清县", "id": "闽清县"}, {"fullName": "永泰县", "id": "永泰县"}, {
        "fullName": "福清市",
        "id": "福清市"
      }, {"fullName": "高新区", "id": "高新区"}],
      countyProps: {"label": "fullName", "value": "id"},
      acceptIspassOptions: [{"fullName": "建议通过", "id": "1"}, {"fullName": "建议整改", "id": "0"}],
      acceptIspassProps: {"label": "fullName", "value": "id"},
      isconfirmOptions: [{"fullName": "确认", "id": "1"}, {"fullName": "未确认", "id": "0"}],
      isconfirmProps: {"label": "fullName", "value": "id"},
      digitizationLevelOptions: [{"fullName": "无等级", "id": "0"}, {"fullName": "一级", "id": "1"}, {
        "fullName": "二级",
        "id": "2"
      }, {"fullName": "三级", "id": "3"}, {"fullName": "四级", "id": "4"}],
      digitizationLevelProps: {"label": "fullName", "value": "id"},
      statusOptions: [{"fullName": "已审核", "id": "2"}, {"fullName": "审核中", "id": "1"}, {"fullName": "等待提交", "id": "0"}],
      statusProps: {"label": "fullName", "value": "id"},
      childIndex: -1,
      isEdit: false,
      interfaceRes: {
        enterpriseName: [],
        enterpriseCreditCode: [],
        county: [],
        phone: [],
        projectId: [],
        projectNames: [],
        digitalProjectContract: [],
        digitalProjectPlan: [],
        transactionRecords: [],
        scanningCopy: [],
        acceptIspass: [],
        isconfirm: [],
        rectificationOpinions: [],
        digitizationLevel: [],
        performanceAcceptanceReport: [],
        digitalEvaluationReport: [],
        status: [],
        creatoruserid: [],
        creatortime: [],
        lastmodifyuserid: [],
        lastmodifytime: [],
      },
    }
  },
  computed: {
    formOperates() {
      return this.setting.formOperates
    }
  },
  watch: {},
  created() {
    this.selectProjectInfo();
    this.getFormById();
    if (this.dataForm.id == null || this.dataForm.id == '' && this.dataForm.id == undefined || this.dataForm.id == 0) {
      this.initDefaultData()
    }
    this.dataValueAll = JSON.parse(JSON.stringify(this.dataForm))
  },
  mounted() {
    this.selectProjectDigitalBudget();
  },
  methods: {
    selectProjectInfo() {
      const userId = this.userInfo.userAccount;
      const roleName = this.userInfo.roleName;
      const url = `http://test-fzzxqy.demo-caii.com/cloud-api2/fzzxqy/select_company_project_info?userId=${userId}`;
      if (roleName === '试点企业') {
        axios.get(url).then(res => {
          this.dataForm.enterpriseName = res.data.data[0].Enterprise_name
          this.dataForm.enterpriseCreditCode = res.data.data[0].Enterprise_credit_code
          this.dataForm.county = res.data.data[0].F_County
          this.dataForm.phone = res.data.data[0].F_Phone
          this.dataForm.projectId = res.data.data.map(item => item.F_Id).join('，')
          this.dataForm.projectNames = res.data.data.map(item => item.F_Project_Name).join('，')
          this.dataForm.digitalProjectContract = res.data.data.map(row => {
            const files = JSON.parse(row.F_Digital_Service_Contract_Files);
            const filteredFiles = files.filter(file => file.fileId !== '65d7fc3260b24a5f691bd2f0.doc');
            return filteredFiles.length > 0 ? {
              projectName: row.F_Project_Name,
              projectFiles: filteredFiles
            } : null;
          }).filter(Boolean); // 过滤掉所有的null值

          this.dataForm.digitalProjectPlan = res.data.data.map(row => {
            const files = JSON.parse(row.F_Digital_Project_Plan_Files);
            const filteredFiles = files.filter(file => file.fileId !== '65d7fc3760b24a5f691bd2f1.docx');
            return filteredFiles.length > 0 ? {
              projectName: row.F_Project_Name,
              projectFiles: filteredFiles
            } : null;
          }).filter(Boolean); // 过滤掉所有的null值
        })
      } else {

      }
    },
    selectProjectDigitalBudget() {
      this.isShowBudget = this.userInfo.roleName.includes("专家组")
      const url = `http://test-fzzxqy.demo-caii.com/cloud-api2/fzzxqyz/projectDigitalBudgetToCheck?checkId=${this.dataForm.id}`
      axios.get(url).then(res => {
        this.projectDigitalBudgetList = res.data.data
        this.otherProjectDigitalBudgetList = res.data.data.filter(project => {
          return project.otherDigitalBudget.length > 0;
        });
      })
    },
    changeData(model, index) {
      this.isEdit = false
      this.childIndex = index
      let modelAll = model.split("-");
      let faceMode = "";
      for (let i = 0; i < modelAll.length; i++) {
        faceMode += modelAll[i];
      }
      for (let key in this.interfaceRes) {
        if (key != faceMode) {
          let faceReList = this.interfaceRes[key]
          for (let i = 0; i < faceReList.length; i++) {
            if (faceReList[i].relationField == model) {
              let options = 'get' + key + 'Options';
              if (this[options]) {
                this[options]()
              }
              this.changeData(key, index)
            }
          }
        }
      }
    },
    changeDataFormData(type, data, model, index, defaultValue) {
      if (!this.isEdit) {
        if (type == 2) {
          for (let i = 0; i < this.dataForm[data].length; i++) {
            if (index == -1) {
              this.dataForm[data][i][model] = defaultValue
            } else if (index == i) {
              this.dataForm[data][i][model] = defaultValue
            }
          }
        } else {
          this.dataForm[data] = defaultValue
        }
      }
    },
    dataAll() {
    },
    selfGetInfo(dataForm) {
      this.dataInfo(dataForm)
    },
    beforeSubmit() {
      this.dataForm.creatoruserid = 'e' + this.dataForm.enterpriseCreditCode
      if (this.eventType === 'save') {
        //暂存
        this.dataForm.status = '0';
      } else if (this.eventType === 'submit') {
        //提交
        this.dataForm.status = '1';
      }
      const _data = this.dataList()
      return _data
    },
    selfInit() {
      this.dataAll()
    },
    getFormById() {
      getFormById("566267928102570309").then(res => {
        this.dataForm.flowId = res.data && res.data.flowId
        // this.encode = res.data&&res.data.encode
      })
    },
    exist() {
      let isOk = true
      for (let key in this.tableRequiredData) {
        if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let item = this.dataForm[key][i]
            inner: for (let id in item) {
              let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
              if (!arr.length) continue inner
              if (arr[0].required) {
                let msg = `${arr[0].name}不能为空`
                let boo = true
                if (arr[0].dataType === 'array') {
                  boo = !this.jnpf.isEmptyArray(item[id])
                } else {
                  boo = !this.jnpf.isEmpty(item[id])
                }
                if (!boo) {
                  this.$message({
                    message: msg,
                    type: 'error',
                    duration: 1000
                  })
                  isOk = false
                  break
                }
              }
            }
          }
        }
      }
      return isOk
    },
    goBack() {
      this.$emit('refresh')
    },
    clearData() {
      this.dataForm = JSON.parse(JSON.stringify(this.dataValueAll))
    },
    //初始化默认数据
    initDefaultData() {

    },
    openSelectDialog(key) {
      this.currTableConf = this.addTableConf[key]
      this.currVmodel = key
      this.selectDialogVisible = true
      this.$nextTick(() => {
        this.$refs.selectDialog.init()
      })
    },
    addForSelect(data) {
      for (let i = 0; i < data.length; i++) {
        let t = data[i]
        if (this['get' + this.currVmodel]) {
          this['get' + this.currVmodel](t)
        }
      }
    },
    dateTime(timeRule, timeType, timeTarget, timeValueData, dataValue) {
      let timeDataValue = null;
      let timeValue = Number(timeValueData)
      if (timeRule) {
        if (timeType == 1) {
          timeDataValue = timeValue
        } else if (timeType == 2) {
          timeDataValue = dataValue
        } else if (timeType == 3) {
          timeDataValue = new Date().getTime()
        } else if (timeType == 4) {
          let previousDate = '';
          if (timeTarget == 1 || timeTarget == 2) {
            previousDate = getDateDay(timeTarget, timeType, timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else if (timeTarget == 3) {
            previousDate = getBeforeData(timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else {
            timeDataValue = getBeforeTime(timeTarget, timeValue).getTime()
          }
        } else if (timeType == 5) {
          let previousDate = '';
          if (timeTarget == 1 || timeTarget == 2) {
            previousDate = getDateDay(timeTarget, timeType, timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else if (timeTarget == 3) {
            previousDate = getLaterData(timeValue)
            timeDataValue = new Date(previousDate).getTime()
          } else {
            timeDataValue = getLaterTime(timeTarget, timeValue).getTime()
          }
        }
      }
      return timeDataValue;
    },
    time(timeRule, timeType, timeTarget, timeValue, formatType, dataValue) {
      let format = formatType == 'HH:mm' ? 'HH:mm:00' : formatType
      let timeDataValue = null
      if (timeRule) {
        if (timeType == 1) {
          timeDataValue = timeValue || '00:00:00'
          if (timeDataValue.split(':').length == 3) {
            timeDataValue = timeDataValue
          } else {
            timeDataValue = timeDataValue + ':00'
          }
        } else if (timeType == 2) {
          timeDataValue = dataValue
        } else if (timeType == 3) {
          timeDataValue = this.jnpf.toDate(new Date(), format)
        } else if (timeType == 4) {
          let previousDate = '';
          previousDate = getBeforeTime(timeTarget, timeValue)
          timeDataValue = this.jnpf.toDate(previousDate, format)
        } else if (timeType == 5) {
          let previousDate = '';
          previousDate = getLaterTime(timeTarget, timeValue)
          timeDataValue = this.jnpf.toDate(previousDate, format)
        }
      }
      return timeDataValue;
    },
    dataList() {
      var _data = this.dataForm;
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll
      this.dataForm = _dataAll
      this.isEdit = true
      this.dataAll()
      this.childIndex = -1
    },
  },
}

</script>
<style lang="scss" scoped>
.main .project-main {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1) !important;
  border: 1px solid #EBEEF5;
  padding: 20px;
  border-radius: 5px;
}

::v-deep .el-textarea__inner {
  min-height: 100px !important;
}

::v-deep .el-input-number--medium {
  width: 100% !important;
}

.file-main {
  display: flex;
  flex-direction: row;

  label {
    color: #606266;
    font-size: 14px;
  }
}
</style>
